package com.diy.common.helper;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.PropertyPlaceholderHelper;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 加载指定文件中的Key-Value值信息
 */
public class PropertyConfigurer extends PropertyPlaceholderConfigurer {

    private static Map<String, Object> ctxPropertiesMap = new HashMap<String, Object>();

    @Override
    protected void processProperties(
            ConfigurableListableBeanFactory beanFactoryToProcess,
            Properties props) throws BeansException {

        PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX,DEFAULT_VALUE_SEPARATOR, false);

        for (Map.Entry<Object, Object> entry : props.entrySet()) {
            String key = String.valueOf(entry.getKey());
            String value = String.valueOf(entry.getValue());
            value = helper.replacePlaceholders(value, props);
            ctxPropertiesMap.put(key, value);
        }
        super.processProperties(beanFactoryToProcess, props);
    }

    /**
     * 获取指定Key对应的值
     * @param name Key名称
     * @param <T> value类型
     * @return
     */
    public static <T> T getPropertyValueByKey(String name) {

        if (StringUtil.isEmpty(name))
            return null;

        return (T) ctxPropertiesMap.get(name);
    }
}
